package cc.magicjson.example.demo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class MontyHallProblemNonJava8 {

    public static void main(String[] args) {
        long totalTrials = 100000L;
        int stayWins = 0, switchWins = 0;

        for (long trial = 0; trial < totalTrials; trial++) {
            List<Prize> doors = new ArrayList<>(Arrays.asList(Prize.CAR, Prize.GOAT, Prize.GOAT));
            Random random = new Random();
            int initialChoiceIndex = random.nextInt(doors.size());
            revealAndRemoveGoat(doors, initialChoiceIndex);

            // 根据策略执行游戏并计数
            if (random.nextBoolean()) {
                stayWins += simulateGameStay(doors, initialChoiceIndex);
            } else {
                switchWins += simulateGameSwitch(doors, initialChoiceIndex);
            }
        }

        System.out.printf("坚持原选择赢得车的概率: %.2f%%\n", (double) stayWins / totalTrials * 100);
        System.out.printf("改变选择赢得车的概率: %.2f%%\n", (double) switchWins / totalTrials * 100);
    }

    private static void revealAndRemoveGoat(List<Prize> doors, int initialChoiceIndex) {
        boolean carFound = false;
        for (int i = 0; i < doors.size(); ) {
            Prize door = doors.get(i);
            if (door == Prize.CAR) {
                carFound = true;
            } else if (carFound && door == Prize.GOAT && i != initialChoiceIndex) {
                doors.remove(i);
                break;
            } else {
                i++;
            }
        }
    }

    private static int simulateGameStay(List<Prize> doors, int initialChoiceIndex) {
        return doors.get(initialChoiceIndex) == Prize.CAR ? 1 : 0;
    }

    private static int simulateGameSwitch(List<Prize> doors, int initialChoiceIndex) {
        int nextAvailableIndex = getNextAvailableDoorIndex(doors, initialChoiceIndex);
        return doors.get(nextAvailableIndex) == Prize.CAR ? 1 : 0;
    }

    private static int getNextAvailableDoorIndex(List<Prize> doors, int currentChoiceIndex) {
        return (currentChoiceIndex + 1) % doors.size();
    }

    public enum Prize {CAR, GOAT}
}
